package com.flex.core.validate;

import java.util.HashMap;
import java.util.Map;

import com.flex.core.validate.annotation.Validation;
import com.flex.core.validate.impl.EmailValidator;
import com.flex.core.validate.impl.IntValidator;
import com.flex.core.validate.impl.RegexValidator;
import com.flex.core.validate.impl.RequiredValidator;
import com.flex.core.validate.impl.StringValidator;
import com.flex.core.validate.impl.UrlValidator;

/**
 * 验证器类，加载各种验证器，并对model进行验证
 * 
 * @author radio
 * 
 */
public class ValidateContext {

	protected static Map<ValidatorType, AbstractValidator> map = new HashMap<ValidatorType, AbstractValidator>();

	/**
	 * 初始化加载所有验证器
	 */
	static {
		map.put(ValidatorType.REQUIRED, new RequiredValidator());
		map.put(ValidatorType.EMAIL, new EmailValidator());
		map.put(ValidatorType.INT, new IntValidator());
		map.put(ValidatorType.REGEX, new RegexValidator());
		map.put(ValidatorType.STRING, new StringValidator());
		map.put(ValidatorType.URL, new UrlValidator());
	}

	/**
	 * 统一验证接口方法。根据属性所配置的验证器去调用相应验证器的验证方法
	 * 
	 * @param validateAnnotation
	 *            验证器注解
	 * @param filedValue
	 *            被验证的属性值
	 * @return 返回验证后的错误信息，验证通过则返回空字符串
	 */
	public static String validate(Validation validateAnnotation,
			Object filedValue) {
		AbstractValidator av = (AbstractValidator) map.get(validateAnnotation
				.type());
		av.setValidation(validateAnnotation);
		av.setFiledValue(filedValue);
		return av.validate();
	}

}
